package com.aptech.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.aptech.dao.UserOperateDao;
import com.aptech.model.UpdateUser;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UpToUser extends ActionSupport{
	
	private UpdateUser user = new UpdateUser();


	public String updateUser(){
		ActionContext context =ActionContext.getContext();
		HttpServletRequest request=ServletActionContext.getRequest();
		UserOperateDao userdao=new UserOperateDao();
		
		//取出存在Session中的用户信息
		String name=context.getSession().get("isLogin").toString();
				
		//先判断页面输入是否合法
		if(user.getUsername().equals("")){
			request.setAttribute("information","用户名不允许为空");
			updateRequest();
			return ERROR;
		}
		if(user.getAge().equals("")){
			request.setAttribute("information","年龄不允许为空");
			updateRequest();
			return ERROR;
		}else{
			String i =user.getAge();
			try{
				int age=Integer.decode(i);	
				if(age>120){
					String s="你能活到"+age+"岁?";
					request.setAttribute("information",s);
					updateRequest();
					return ERROR;
				}
			}catch(Exception e){
				request.setAttribute("information","年龄出入不合法");
				updateRequest();
				return ERROR;
			}
		}
		if(user.getPhone().equals("")){
			request.setAttribute("information","电话不允许为空");
			updateRequest();
			return ERROR;
		}
		if(user.getPhone().length()!=11){
			Boolean b=user.getPhone().matches("\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d\\d");
			if(b==false){
				request.setAttribute("information","请填写11位正确手机号码");
				updateRequest();
				return ERROR;
			}
		}
		if(user.getAddress().equals("")){
			request.setAttribute("information","地址不允许为空");
			updateRequest();
			return ERROR;
		}
		
		//调用UserProfileDao层方法
		String st=userdao.updateUser(user,name);
		if(st=="nameerror"){
			request.setAttribute("information","该用户名已被使用");
			//更新request值
			updateRequest();
			return ERROR;
		}
		
		//更新request值
		updateRequest();
		return st;
	}
	
	//更新request值
	public void updateRequest(){
		HttpServletRequest request=ServletActionContext.getRequest();
		request.setAttribute("userName",user.getUsername());
		request.setAttribute("age",user.getAge());
		request.setAttribute("sex",user.getSex());
		request.setAttribute("phone",user.getPhone());
		request.setAttribute("address",user.getAddress());
	}
	
	
	public UpdateUser getUser() {
		return user;
	}

	public void setUser(UpdateUser user) {
		this.user = user;
	}
	
	
}
